<template>
  <div class="box">
    <h1>预储/社团 年龄分布情况</h1>
    <div class="chart" ref="chart"></div>
  </div>
</template>

<script setup lang="ts">
import * as echarts from 'echarts';
import { onMounted, onUnmounted, ref } from 'vue';
import { getLeftCenterMainChartData } from '@/api/data-screen/LeftChart';
import { useRouter } from 'vue-router';
const router = useRouter();

// 定义接口类型
interface AgeData {
  male: number[];
  female: number[];
}

interface ChartData {
  reserve: {
    total: number;
    ages: AgeData;
    genderCount: {
      male: number;
      female: number;
    };
  };
  club: {
    total: number;
    ages: AgeData;
    genderCount: {
      male: number;
      female: number;
    };
  };
}



const ages = [18, 19, 20, 21, 22, 23, 24, 25, 26];
const initData = async () => {
  try {
    return await getLeftCenterMainChartData(ages);
  } catch {
    console.log("获取左中主图数据失败！")
  }
}

const chart = ref<HTMLElement | null>(null);
// 初始化
let chartInstance: echarts.ECharts | null = null;
const initChart = () => {
  if (chart.value) {
    chartInstance = echarts.init(chart.value);
    updateChart();
  }
};
const updateChart = async () => {
  try {
    const response = await initData();
    if (!response?.data) return; // 添加空值保护
    const chartData = response.data;

    // 处理预储数据
    const reserveMaleData = chartData.reserve.ages.male;
    const reserveFemaleData = chartData.reserve.ages.female;

    // 处理军事社团数据
    const militaryMaleData = chartData.club.ages.male;
    const militaryFemaleData = chartData.club.ages.female;

    const option = {
      tooltip: {},
      //图例
      legend: {
        data: ['男', '女', '总和'],
        bottom: '45%',
        left: '40%',
        textStyle: {
          fontSize: 17,// 调整字体大小
          color: '#ccc'
        }
      },
      title: [
        {
          text: '预储',
          subtext: `总计 ${chartData.reserve.total}`,
          left: '25%',
          textAlign: 'center',
          textStyle: {
            color: '#00BFFF' // 标题颜色
          },
          subtextStyle: {
            color: '#00FF00' // 副标题颜色
          }
        },
        {
          text: '军事兴趣类社团',
          subtext: `总计 ${chartData.club.total}`,
          left: '25%',
          top: '50%',
          textAlign: 'center',
          textStyle: {
            color: '#00BFFF' // 标题颜色
          },
          subtextStyle: {
            color: '#00FF00' // 副标题颜色
          }
        },
      ],
      grid: [
        {
          top: 49,
          width: '58%',
          bottom: '51%',
          left: 25,
          containLabel: true
        },
        {
          top: '58%',
          width: '58%',
          bottom: 5,
          left: 25,
          containLabel: true
        }
      ],
      xAxis: [
        {
          type: 'value',
          //max: 300,
          splitLine: {
            show: false
          },
          axisLabel: {
            color: '#ccc' // 调整轴标签字体颜色
          },
          name: '人数/人',
          nameLocation: 'end',
          nameGap: 10,
          nameTextStyle: {
            color: '#00BFFF', // 调整轴标题字体颜色
            fontSize: 14
          },
          axisTick: {
            show: true // 显示刻度
          }
        },
        {
          type: 'value',
          //max: 300,
          gridIndex: 1,
          splitLine: {
            show: false
          },
          axisLabel: {
            color: '#ccc' // 调整轴标签字体颜色
          },
          name: '人数/人',
          nameLocation: 'end',
          nameGap: 10,
          nameTextStyle: {
            color: '#00BFFF', // 调整轴标题字体颜色
            fontSize: 14
          },
          axisTick: {
            show: true // 显示刻度
          }
        }
      ],
      yAxis: [
        {
          type: 'category',
          data: ages.map(age => age.toString()),
          axisLabel: {
            interval: 0,
            rotate: 30,//倾斜度
            color: '#ccc' // 调整轴标签字体颜色
          },
          splitLine: {
            show: false
          }
          // name: '年龄/岁',
          // nameLocation: 'end',
          // nameGap: 20,
          // nameTextStyle: {
          //   color: '#ccc', // 调整轴标题字体颜色
          //   fontSize: 14
          // },
        },
        {
          gridIndex: 1,
          type: 'category',
          data: ages.map(age => age.toString()),
          axisLabel: {
            interval: 0,
            rotate: 30,
            color: '#ccc' // 调整轴标签字体颜色
          },
          splitLine: {
            show: false
          },
          name: '年龄/岁',
          nameLocation: 'end',
          nameGap: 25,
          nameTextStyle: {
            color: '#1E90FF', // 调整轴标题字体颜色
            fontSize: 14,
            fontWeight: 'bold' // 字体加粗（可选
          }
        }
      ],
      series: [
        {
          name: '男',
          type: 'bar',
          stack: 'chart',
          z: 3,
          label: {
            position: 'insideRight', // 柱子内部右侧显示值
            show: true,
            color: '#fff', // 调整字体颜色
            formatter: '{c}' // 显示具体数值
          },
          data: reserveMaleData,
        },
        {
          name: '女',
          type: 'bar',
          stack: 'chart',
          // silent: true,
          itemStyle: {
            color: '#FFB6C1'
          },
          label: {
            position: 'insideRight', // 柱子内部右侧显示值
            show: true,
            color: 'black', // 调整字体颜色
            formatter: '{c}' // 显示具体数值
          },
          data: reserveFemaleData,
        },
        // 新增的透明柱子，显示男女之和
        {
          name: '总和',
          type: 'bar',
          stack: 'chart',
          itemStyle: {
            color: '#ccc', // 颜色
          },
          label: {
            position: 'right', // 柱子顶部显示值
            show: true,
            color: '#fff', // 调整字体颜色
            fontWeight: 'bold', // 加粗字体
            formatter: (params: any) => {
              return reserveMaleData[params.dataIndex] + reserveFemaleData[params.dataIndex];
            }
          },
          data: new Array(ages.length).fill(0)
        },
        {
          name: '男',
          type: 'bar',
          stack: 'component',
          xAxisIndex: 1,
          yAxisIndex: 1,
          z: 3,
          label: {
            position: 'insideRight', // 柱子内部右侧显示值
            show: true,
            color: '#fff', // 调整字体颜色
            formatter: '{c}' // 显示具体数值
          },
          data: militaryMaleData,
        },
        {
          name: '女',
          type: 'bar',
          stack: 'component',
          // silent: true,
          xAxisIndex: 1,
          yAxisIndex: 1,
          itemStyle: {
            color: '#FFA07A'
          },
          label: {
            position: 'insideRight', // 柱子内部右侧显示值
            show: true,
            color: 'black', // 调整字体颜色
            formatter: '{c}' // 显示具体数值
          },
          data: militaryFemaleData,
        },
        // 第二个柱状图的透明柱子，显示男女之和
        {
          name: '总和',
          type: 'bar',
          stack: 'component',
          xAxisIndex: 1,
          yAxisIndex: 1,
          itemStyle: {
            color: '#ccc' //
          },
          label: {
            position: 'right', // 柱子顶部显示值
            show: true,
            color: '#fff', // 调整字体颜色
            fontWeight: 'bold', // 加粗字体
            formatter: (params: any) => {
              return militaryMaleData[params.dataIndex] + militaryFemaleData[params.dataIndex];
            }
          },
          data: new Array(ages.length).fill(0)
        },
        {
          type: 'pie',
          radius: ['0%', '25%'],
          center: ['80%', '25%'],
          label: {
            show: true,
            position: 'inside', // 值显示在内部
            formatter: '{b}: {c} \n ({d}%)' // 显示名称、值和百分比
          },
          data: [
            {
              value: chartData.reserve.genderCount.male,
              name: '男'
            },
            {
              value: chartData.reserve.genderCount.female,
              name: '女'
            }
          ]
        },
        {
          type: 'pie',
          radius: [0, '25%'],
          center: ['80%', '75%'],
          label: {
            show: true,
            position: 'inside', // 值显示在内部
            formatter: '{b}: {c} \n ({d}%)' // 显示名称、值和百分比
          },
          data: [
            {
              value: chartData.club.genderCount.male,
              name: '男'
            },
            {
              value: chartData.club.genderCount.female,
              name: '女'
            }
          ]
        }
      ]
    };

    option && chartInstance.setOption(option);


    chartInstance.on('click', function (params) {
      if (params.seriesType === 'bar' && (params.seriesName === '男' || params.seriesName === '女')) {

        // 判断是预储还是社团区域
        const isPreReserve = params.seriesIndex < 3;
        const category = isPreReserve ? '预储' : '社团';


        const gender = params.seriesName; // 获取性别
        const age = params.name; // 获取年龄（假设 y 轴为年龄）
        console.log(age)
        const value = params.value; // 获取人数
        // alert(`类别: ${category}\n性别: ${gender}\n年龄: ${age}\n人数: ${value}`);
        router.push({
          path: '/admin/preReserve/memberManage',
          query: {
            gender: gender === '男' ? 1 : 0,
            ageMin: age,
            ageMax: age,
            page: 1,
            pageSize: 5,
          }
        })
      }
      else if (params.seriesType === 'pie') {
        const category = params.seriesIndex === 6 ? '预储' : '社团';
        const gender = params.name;
        const value = params.value;
        // alert(`类别: ${category}\n性别: ${gender}\n人数: ${value}`);
      }
    });
  } catch (error) {
    console.log('左中主图渲染失败！')
  }
}




onMounted(() => {
  initChart();
})

onUnmounted(() => {
  if (chartInstance) {
    chartInstance.dispose();
  }
  window.removeEventListener('resize', () => { });
});
</script>

<style scoped>
.box {
  height: 100%;
  width: 100%;
  align-items: center;
  justify-content: center;
}

.chart {
  height: 85%;
  width: 97%;
}

h1 {
  text-align: center;
  color: aliceblue;
  margin: 0;
  margin-top: 1rem;
  padding: 0;
}
</style>